﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Linq;
using System.Data.SqlClient;
using E0XPayService.Utils;
using Newtonsoft.Json.Linq;

namespace E0XPayService.Web
{
    public partial class notify : System.Web.UI.Page
    {
        static Log logger = LogFactory.GetLogger("CallLog");

        protected void Page_Load(object sender, EventArgs e)
        {
            var log = new CallLog() { OperationName = "notify" };

            JObject response = new JObject();
            response["status"] = -1;
            response["message"] = "POST ONLY!";

            try
            {
                if (Request.RequestType == "POST")
                {
                    response = callback(log);
                }

                Response.Write(response);
            }
            catch (Exception ex)
            {
                response["status"] = -5;
                response["message"] = ex.ToString();
                Response.Write(response);
            }

            log.ResponseDetail = JsonConvert.SerializeObject(response);
            logger.Info(log);
        }
        public JObject callback(CallLog log)
        {
            var result = new JObject();
            var inputParams = "";

            //初始化数据
            using (StreamReader sr = new StreamReader(Request.InputStream))
            {
                inputParams = sr.ReadToEnd();
            }
            log.RequestDetail = inputParams;

            var queryString = HttpUtility.ParseQueryString(inputParams);
            Dictionary<string, string> inputDict = queryString.AllKeys.ToDictionary(x => x, x => queryString[x]);
           
            if (E0XUtils.NorifyContentCheckSign(JsonConvert.SerializeObject(inputDict)))
            {
                if (inputDict["status"] == "1")
                {
                    try
                    {
                        var mch_id = GetValueFromDict(inputDict, "mch_id"); //商户号
                        var sign = GetValueFromDict(inputDict, "sign"); //签名
                        var pt = GetValueFromDict(inputDict, "pt"); //渠道代码
                        var channel = GetValueFromDict(inputDict, "channel"); //通道代码
                        var status = GetValueFromDict(inputDict, "status"); //交易状态
                        var total_fee = GetValueFromDict(inputDict, "total_fee"); //总金额
                        var trade_no = GetValueFromDict(inputDict, "trade_no"); //支付订单号
                        var out_trade_no = GetValueFromDict(inputDict, "out_trade_no"); //商户订单号
                        var attach = GetValueFromDict(inputDict, "attach"); //附加信息
                        var paid_at = GetValueFromDict(inputDict, "paid_at"); //交易时间

                        SqlParameter[] parameters = {
                            new SqlParameter("@TranType", "InsertNotifyResult"),
                            new SqlParameter("@mch_id", mch_id),
                            new SqlParameter("@sign", sign),
                            new SqlParameter("@pt", pt),
                            new SqlParameter("@channel", channel),
                            new SqlParameter("@status", status),
                            new SqlParameter("@total_fee", total_fee),
                            new SqlParameter("@trade_no", trade_no),
                            new SqlParameter("@out_trade_no", out_trade_no),
                            new SqlParameter("@attach", attach),
                            new SqlParameter("@paid_at", paid_at),
                        };
                        DBHelper.ExecuteNonQuerySP("NotifyResult_E0X", parameters);

                        logger.Info("执行保存");

                        result["status"] = 0;
                        result["message"] = "OK";
                    }
                    catch (Exception ex)
                    {
                        result["status"] = -2;
                        result["message"] = ex.Message;
                        logger.Error(new CallErrorLog(JSONHelper.Serialize(log), ex));
                    }
                }
                else
                {
                    var err_code = GetValueFromDict(inputDict, "status"); //返回代码

                    result["status"] = -3;
                    result["message"] = "status is not equal to 1!";
                    logger.Error(new CallErrorLog(JSONHelper.Serialize(log), "支付通知异常。结果并非支付成功！", string.Format("code:{0}", err_code)));
                }
            }
            else
            {
                result["status"] = -4;
                result["message"] = "Signature validation failed!";
                logger.Error(new CallErrorLog(JSONHelper.Serialize(log), "系统提醒：平台签名验签不通过。"));
            }

            return result;
        }

        private static string GetValueFromDict(IDictionary<string, string> dict, string key)
        {
            return (dict.ContainsKey(key) && dict[key] != null) ? dict[key] : "";
        }
    }
}